package com.ynwa.jvm;

import javax.print.attribute.standard.NumberUp;

/**
 * 对象在finalize()方法中拯救自己
 *
 * @author gzd
 * @date 2019-06-22 23:04
 */
public class FinalizeMethodTest {
    public static FinalizeMethodTest SAVE_HOOK = null;

    public void isAlive() {
        System.out.println("我还活着");
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize()方法被执行了!");
        SAVE_HOOK = this;
    }

    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeMethodTest();

        // 对象第一次成功拯救自己
        SAVE_HOOK = null;
        System.gc();
        // finalize方法优先级很低, 所以暂停1秒来等他
        Thread.sleep(1000);
        if (SAVE_HOOK != null){
            SAVE_HOOK.isAlive();
        }else {
            System.out.println("我被回收了");
        }

        // 下面这个代码和上面一样, 但是拯救失败了

        SAVE_HOOK = null;
        System.gc();
        // finalize方法优先级很低, 所以暂停1秒来等他
        Thread.sleep(1000);
        if (SAVE_HOOK != null){
            SAVE_HOOK.isAlive();
        }else {
            System.out.println("我被回收了");
        }
    }
}
